package org.gwu.seuss.admin;

import java.io.IOException;

import org.gwu.seuss.admin.commandline.AdminValidator;
import org.gwu.seuss.admin.commandline.AdministratorCommandLineArgs;
import org.gwu.seuss.communication.domain.UserTO;
import org.gwu.seuss.communication.request.Actions;
import org.gwu.seuss.communication.request.ClientRequest;
import org.gwu.seuss.communication.request.ServerResponse;
import org.gwu.seuss.communication.util.FileUtils;
import org.gwu.seuss.ui.CommandLineInterface;
import org.gwu.seuss.ui.commandline.BaseCommandLineArgs;
import org.gwu.seuss.ui.connection.SSLConnectionHandler;
import org.gwu.seuss.ui.exception.NoArgumentsProvidedException;
import org.kohsuke.args4j.CmdLineParser;

//import org.gwu.seuss.admin.commandline.AdminValidator;

public class AdministratorInterface extends CommandLineInterface {

	@Override
	public void init() {
		// TODO Spring like stuff
		connectionHandler = new SSLConnectionHandler();
		validator = new AdminValidator();
		bcla = new AdministratorCommandLineArgs();
		parser = new CmdLineParser(bcla);
	}

	@Override
	public String handleServerResponse(ClientRequest cr, ServerResponse sr)
			throws Exception {
		//TODO: Going over with professor on Monday
		if (cr.getAction().equals(Actions.SHOW_EVENT_LOG)) {
			FileUtils.writeFile(sr.getFilename(), "event.log",
					sr.getFileBytes());
		}
		return sr.getMessage();
	}

	@Override
	public <T extends BaseCommandLineArgs> ClientRequest getClientRequest(T cli)
			throws IOException, NoArgumentsProvidedException {

		ClientRequest cr = setUpClientRequest(cli);
		AdministratorCommandLineArgs cla = (AdministratorCommandLineArgs) cli;

		if (cla.getDisableUsername() != null) {
			cr.setAction(Actions.DISABLE_USER);
			cr.setUser(new UserTO(cla.getDisableUsername()));
		} else if (cla.getEnableUsername() != null) {
			cr.setAction(Actions.ENABLE_USER);
			cr.setUser(new UserTO(cla.getEnableUsername()));
		} else if (cla.getNewLoginName() != null) {
			cr.setAction(Actions.CREATE_USER);
			cr.setUser(new UserTO(cla.getNewLoginName(), new String(cla.retrievePassword())));
		} else if (cla.getRemoveUsername() != null) {
			cr.setAction(Actions.REMOVE_USER);
			cr.setUser(new UserTO(cla.getRemoveUsername()));
		} else {
			throw new NoArgumentsProvidedException();
		}

		return cr;
	}

	@Override
	public String getPropertiesFile() {
		return "admin.properties";
	}

}
